package com.umeng.p7qimokaoshi;

import android.app.Application;
import android.util.Log;

import com.example.myhttp.global.GlobalConfig;
import com.example.myhttp.utils.LogUtils;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                LogUtils.e(message);
            }
        });
        AppendUrlParamIntentcenpter appendUrlParamIntentcenpter = new AppendUrlParamIntentcenpter();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        GlobalConfig.getInstance()
                .addInterceptors(httpLoggingInterceptor)
                .addInterceptors(appendUrlParamIntentcenpter);

    }

    public class AppendUrlParamIntentcenpter implements Interceptor{
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request oldRequest = chain.request();

            //拿到拥有以前的request里的url的那些信息的builder
            HttpUrl.Builder builder = oldRequest
                    .url()
                    .newBuilder();
            //https://api.zhuge.com/home/v1/Appindex/showHighOpinion?cityid=1&operaVersion=5.1.1
                //得到新的url(已经追加了参数)
            HttpUrl newUrl = builder.addEncodedQueryParameter("cityid", "1")
                    .addQueryParameter("operaVersion", "5.1.1")
                    .build();
            for (int i = 0; i <newUrl.querySize(); i++) {
                Log.e("TAG", "intercept: "+newUrl.queryParameterName(i)+newUrl.queryParameterValue(i));
            }
            //利用新的Url，构建新的request,并打送给服务器
            Request newRequest = oldRequest
                    .newBuilder()
                    .url(newUrl)
                    .url(newUrl)
                    .build();
            return chain.proceed(newRequest);
        }
    }
}

